package com.aij.ims.handler;

import com.aij.ims.entity.Message;
import com.aij.ims.utils.SpringUtil;
import com.aij.starter.service.AijService;
import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 自定义处理器
 * <pre>
 *     继承SimpleChannelInboundHandler<TextWebSocketFrame>并实现channelRead0（通道读取）
 * </pre>
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	
	private static AijService aijService;
	static {
		aijService = SpringUtil.getBean(AijService.class);
	}

    /**
     * 创建ChannelGroup对象存储所有连接的用户
     */
	public static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 有新消息时会调用这个方法
     *
     * @param channelHandlerContext 上下文处理器
     * @param textWebSocketFrame    文本
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //获取客户端发送的消息内容
        String text = textWebSocketFrame.text();
        System.out.println("收到客户端发送来的消息:  " + text);
		Message msg = JSON.parseObject(text, Message.class);
		aijService.runLlm(msg.params.body, new LlmHandler(msg, channelHandlerContext.channel()));
    }
    
    /**
     * 有新的连接建立时
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //加入通道组
        clients.add(ctx.channel());
    }
    
    /**
     * 不活跃时会调用这个方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //移除出通道组
        clients.remove(ctx.channel());
    }

}
